package uestc.lj.gulishop.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import uestc.lj.common.constant.OrderConstant;
import uestc.lj.common.exception.NoStockException;
import uestc.lj.common.to.OrderEntityTO;
import uestc.lj.common.to.SeckillOrderTO;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.common.utils.R;
import uestc.lj.common.vo.MemberResponseVO;
import uestc.lj.gulishop.order.dao.OrderDao;
import uestc.lj.gulishop.order.entity.OrderEntity;
import uestc.lj.gulishop.order.entity.OrderItemEntity;
import uestc.lj.gulishop.order.entity.PaymentInfoEntity;
import uestc.lj.gulishop.order.enume.OrderStatusEnum;
import uestc.lj.gulishop.order.feign.CartFeignService;
import uestc.lj.gulishop.order.feign.MemberFeignService;
import uestc.lj.gulishop.order.feign.ProductFeignService;
import uestc.lj.gulishop.order.feign.WareFeignService;
import uestc.lj.gulishop.order.interceptor.LoginUserInterceptor;
import uestc.lj.gulishop.order.service.OrderItemService;
import uestc.lj.gulishop.order.service.OrderService;
import uestc.lj.gulishop.order.service.PaymentInfoService;
import uestc.lj.gulishop.order.to.OrderCreateTO;
import uestc.lj.gulishop.order.vo.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    ThreadLocal<OrderSubmitVO> submitVOThreadLocal = new ThreadLocal<>();

    /**
     * 展示当前登录用户的订单数据
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取当前登录用户
        MemberResponseVO memberResponseVO = LoginUserInterceptor.loginUser.get();
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberResponseVO.getId()).orderByDesc("id");
        // 条件查询
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params), wrapper);
        // 封装订单的订单项
        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            // 查询订单的订单项
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        // 1.获取当前登录用户
        MemberResponseVO memberResponseVO = LoginUserInterceptor.loginUser.get();
        Long memberId = memberResponseVO.getId();

        // 在异步执行之前提前将cookie设置进header中
        // 获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 2.远程查询会员的收获地址
        CompletableFuture<Void> getMemberAddressTask = CompletableFuture.runAsync(() -> {
            // 共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R address = memberFeignService.getAddress(memberId);
            if (address.getCode() == 0) {
                List<MemberAddressVO> memberAddress = address.getData("memberAddress", new TypeReference<List<MemberAddressVO>>() {
                });
                orderConfirmVO.setAddress(memberAddress);
            }
        }, threadPoolExecutor);

        // 3.远程查询购物车所选中的商品
        CompletableFuture<Void> getCartItemsTask = CompletableFuture.runAsync(() -> {
            // 共享之前的请求
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R currentCartItems = cartFeignService.getCurrentCartItems();
            if (currentCartItems.getCode() == 0) {
                List<OrderItemVO> cartItems = currentCartItems.getData("cartItems", new TypeReference<List<OrderItemVO>>() {
                });
                orderConfirmVO.setItems(cartItems);
            }
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 查询每件商品项是否有货
            List<OrderItemVO> items = orderConfirmVO.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVO::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStock(skuIds);
            if (r.getCode() == 0) {
                List<SkuStockVO> skuStockVOList = r.getData(new TypeReference<List<SkuStockVO>>() {
                });
                if (skuStockVOList != null) {
                    Map<Long, Boolean> stocks = skuStockVOList.stream().collect(Collectors.toMap(SkuStockVO::getSkuId, SkuStockVO::getHasStock));
                    orderConfirmVO.setStocks(stocks);
                }
            }
        }, threadPoolExecutor);

        // 4.远程查询用户积分
        Integer integration = memberResponseVO.getIntegration();
        orderConfirmVO.setIntegration(integration);
        //  5.防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        orderConfirmVO.setOrderToken(token);
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX + memberId, token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getMemberAddressTask, getCartItemsTask).get();
        return orderConfirmVO;
    }

    @GlobalTransactional
    @Transactional
    @Override
    public submitOrderResponseVO submitOrder(OrderSubmitVO orderSubmitVO) {
        // 将需要共享的数据放入threadLocal
        submitVOThreadLocal.set(orderSubmitVO);

        submitOrderResponseVO submitOrderResponseVO = new submitOrderResponseVO();

        // 1.验证令牌---->保证原子性
        MemberResponseVO memberResponseVO = LoginUserInterceptor.loginUser.get();
        String orderToken = orderSubmitVO.getOrderToken();
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.ORDER_TOKEN_PREFIX + memberResponseVO.getId()), orderToken);
        if (result == 1L) {
            // 2.创建订单
            OrderCreateTO order = createOrder();
            // 3.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVO.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 4.保存订单
                saveOrder(order);
                // 5.远程调用锁定库存----> 分布式事务问题
                WareSkuLockVO wareSkuLockVO = new WareSkuLockVO();
                wareSkuLockVO.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVO> orderitemvos = order.getOrderItems().stream().map(item -> {
                    OrderItemVO orderItemVO = new OrderItemVO();
                    orderItemVO.setSkuId(item.getSkuId());
                    orderItemVO.setCount(item.getSkuQuantity());
                    orderItemVO.setTitle(item.getSkuName());
                    return orderItemVO;
                }).collect(Collectors.toList());
                wareSkuLockVO.setLocks(orderitemvos);
                // 远程调用锁定库存
                R lockStocks = wareFeignService.lockStocks(wareSkuLockVO);
                if (lockStocks.getCode() != 0) {
                    // 锁定失败
                    submitOrderResponseVO.setCode(3);
                    throw new NoStockException();
                } else {
                    // 库存锁定成功，订单创建成功，发送消息进入延迟MQ
                    submitOrderResponseVO.setCode(200);
                    submitOrderResponseVO.setOrder(order.getOrder());
                    try {
                        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    } catch (Exception e) {
                        // 网络异常导致消息丢失

                    }
                }
            } else {
                submitOrderResponseVO.setCode(2);
            }
        } else {
            submitOrderResponseVO.setCode(1);
        }
        return submitOrderResponseVO;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        return baseMapper.selectOne(wrapper);

    }

    /**
     * 超时关闭订单
     *
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        // 1.查询当前订单的状态
        OrderEntity entity = baseMapper.selectById(orderEntity.getId());
        // 待付款才执行关单
        if (entity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            OrderEntity order = new OrderEntity();
            order.setId(entity.getId());
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            baseMapper.updateById(order);
            // 关单成功后，发送释放订单消息给mq
            OrderEntityTO orderEntityTO = new OrderEntityTO();
            BeanUtils.copyProperties(entity, orderEntityTO);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderEntityTO);
        }
    }

    /**
     * 根据订单号获取订单的支付信息
     *
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getPayOrder(String orderSn) {
        PayVo payVo = new PayVo();
        // 1.查询订单
        OrderEntity order = getOrderByOrderSn(orderSn);
        // 2.转换支付总金额，包括额度的转换和类型的转换
        String payAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString();
        payVo.setTotal_amount(payAmount);

        payVo.setOut_trade_no(order.getOrderSn());
        // 3.设置支付标题
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        String subject = "";
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            subject = subject + orderItemEntity.getSkuName();
        }
        payVo.setSubject(subject);
        // 4.设置支付备注
        payVo.setBody(subject);
        return payVo;
    }

    /**
     * 处理支付宝的支付结果
     *
     * @param payAsyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        // 1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());

        paymentInfoService.save(paymentInfoEntity);

        // 2.修改订单的状态
        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TARDE_FINISHED")) {
            // 支付成功
            String outTradeNo = payAsyncVo.getOut_trade_no();
            baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 创建秒杀单的详细信息
     *
     * @param seckillOrderTO
     */
    @Override
    public void createSeckillOrder(SeckillOrderTO seckillOrderTO) throws ExecutionException, InterruptedException {
        // 1.保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        // 订单号
        orderEntity.setOrderSn(seckillOrderTO.getOrderSn());
        // 用户id
        orderEntity.setMemberId(seckillOrderTO.getMemberId());
        // 订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 订单运费
        orderEntity.setFreightAmount(new BigDecimal("52.5"));
        // 订单支付总金额
        BigDecimal payAmount = seckillOrderTO.getSeckillPrice().multiply(BigDecimal.valueOf(seckillOrderTO.getNum()));
        orderEntity.setPayAmount(payAmount);
        // 保存
        baseMapper.insert(orderEntity);
        // 2.保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 订单号
        orderItemEntity.setOrderSn(seckillOrderTO.getOrderSn());
        // 订单支付金额
        orderItemEntity.setRealAmount(payAmount);
        // 订单spu信息
        CompletableFuture<Void> spuTask = CompletableFuture.runAsync(() -> {
            R spuInfo = productFeignService.getSpuInfoBySkuId(seckillOrderTO.getSkuId());
            if (spuInfo.getCode() == 0) {
                spuInfoVO spuInfoVO = spuInfo.getData(new TypeReference<spuInfoVO>() {
                });
                orderItemEntity.setSpuId(spuInfoVO.getId());
                orderItemEntity.setSpuName(spuInfoVO.getSpuName());
            }
        }, threadPoolExecutor);

        CompletableFuture<Void> skuTask = CompletableFuture.runAsync(() -> {
            // 订单sku信息
            R skuInfo = productFeignService.skuInfo(seckillOrderTO.getSkuId());
            if (skuInfo.getCode() == 0) {
                skuInfoVO skuInfoVO = skuInfo.getData("skuInfo", new TypeReference<skuInfoVO>() {
                });
                orderItemEntity.setSkuId(skuInfoVO.getSkuId());
                orderItemEntity.setSkuName(skuInfoVO.getSkuName());
                orderItemEntity.setSkuPic(skuInfoVO.getSkuDefaultImg());
                // 购买数量
                orderItemEntity.setSkuQuantity(seckillOrderTO.getNum());
            }
        }, threadPoolExecutor);

        CompletableFuture.allOf(spuTask, skuTask).get();
        // 保存订单项
        orderItemService.save(orderItemEntity);
    }


    /**
     * 保存订单
     *
     * @param order
     */
    private void saveOrder(OrderCreateTO order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 构建订单
     *
     * @return
     */
    private OrderCreateTO createOrder() {
        OrderSubmitVO orderSubmitVO = submitVOThreadLocal.get();

        OrderCreateTO order = new OrderCreateTO();
        // 1.订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);

        MemberResponseVO memberResponseVO = LoginUserInterceptor.loginUser.get();
        orderEntity.setMemberId(memberResponseVO.getId());
        // 2.远程调用获取收货地址信息和运费信息
        R fare = wareFeignService.getFare(orderSubmitVO.getAddrId());
        if (fare.getCode() == 0) {
            FareResponseVO fareResponseVO = fare.getData("fare", new TypeReference<FareResponseVO>() {
            });
            // 运费
            orderEntity.setFreightAmount(fareResponseVO.getFare());
            // 收货信息
            orderEntity.setReceiverCity(fareResponseVO.getMemberAddressVO().getCity());
            orderEntity.setReceiverDetailAddress(fareResponseVO.getMemberAddressVO().getDetailAddress());
            orderEntity.setReceiverName(fareResponseVO.getMemberAddressVO().getName());
            orderEntity.setReceiverPhone(fareResponseVO.getMemberAddressVO().getPhone());
            orderEntity.setReceiverPostCode(fareResponseVO.getMemberAddressVO().getPostCode());
            orderEntity.setReceiverProvince(fareResponseVO.getMemberAddressVO().getProvince());
            orderEntity.setReceiverRegion(fareResponseVO.getMemberAddressVO().getRegion());
            // 设置默认订单状态信息
            orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            orderEntity.setAutoConfirmDay(14);
        }
        // 3.远程调用获取订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        // 4.验价
        computePrice(orderEntity, orderItemEntities);

        order.setOrder(orderEntity);
        order.setOrderItems(orderItemEntities);
        return order;
    }

    /**
     * 计算订单的价格
     *
     * @param orderEntity       订单
     * @param orderItemEntities 所有购物项
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal couponAmount = new BigDecimal("0.0");
        BigDecimal integrationAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        // 订单总额
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            couponAmount = couponAmount.add(orderItemEntity.getCouponAmount());
            integrationAmount = integrationAmount.add(orderItemEntity.getIntegrationAmount());
            promotionAmount = promotionAmount.add(orderItemEntity.getPromotionAmount());
            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth().toString()));
            total = total.add(orderItemEntity.getRealAmount());
        }
        // 设置金额
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        // 设置积分
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 构建订单项
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        R cartItems = cartFeignService.getCurrentCartItems();
        if (cartItems.getCode() == 0) {
            List<OrderItemVO> cartItemsData = cartItems.getData("cartItems", new TypeReference<List<OrderItemVO>>() {
            });
            if (cartItemsData != null && cartItemsData.size() > 0) {
                return cartItemsData.stream().map(cartItem -> {
                    OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                    orderItemEntity.setOrderSn(orderSn);
                    return orderItemEntity;
                }).collect(Collectors.toList());
            }
        }
        return null;
    }

    /**
     * 构建某一项订单
     *
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO orderItemVO) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1.商品的spu信息
        Long skuId = orderItemVO.getSkuId();
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        if (spuInfo.getCode() == 0) {
            spuInfoVO spuInfoVO = spuInfo.getData(new TypeReference<spuInfoVO>() {
            });
            orderItemEntity.setSpuId(spuInfoVO.getId());
            orderItemEntity.setSpuName(spuInfoVO.getSpuName());
            orderItemEntity.setCategoryId(spuInfoVO.getCatalogId());
            R brandEntity = productFeignService.info(spuInfoVO.getBrandId());
            if (brandEntity.getCode() == 0) {
                BrandVO brand = brandEntity.getData("brand", new TypeReference<BrandVO>() {
                });
                orderItemEntity.setSpuBrand(brand.getName());
            }
        }
        // 2.商品的sku信息
        orderItemEntity.setSkuId(orderItemVO.getSkuId());
        orderItemEntity.setSkuName(orderItemVO.getTitle());
        orderItemEntity.setSkuPrice(orderItemVO.getPrice());
        orderItemEntity.setSkuPic(orderItemVO.getImage());
        String skuAttr = StringUtils.collectionToDelimitedString(orderItemVO.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(orderItemVO.getCount());
        // 3.积分信息
        orderItemEntity.setGiftGrowth(orderItemVO.getPrice().multiply(BigDecimal.valueOf(orderItemVO.getCount())).intValue() / 10);
        orderItemEntity.setGiftIntegration(orderItemVO.getPrice().multiply(BigDecimal.valueOf(orderItemVO.getCount())).intValue() / 10);
        // 4.订单项的价格信息
        BigDecimal discountPrice = new BigDecimal("0.0");
        orderItemEntity.setPromotionAmount(discountPrice);
        orderItemEntity.setCouponAmount(discountPrice);
        orderItemEntity.setIntegrationAmount(discountPrice);
        BigDecimal price = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal payPrice = price.subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(payPrice);


        return orderItemEntity;
    }
}